import { Context, h, Schema } from 'koishi'
import { before } from 'node:test';

export const name = 'qq-group-avatar'

export interface Config {
  verboseSessionOutput: boolean,
}

export const Config: Schema<Config> = Schema.intersect([
  Schema.object({
    verboseSessionOutput: Schema.boolean().default(false).description('是否在日志中输出会话信息'),
  }).description('输出'),
])

export const usage = `
https://blog.csdn.net/weixin_51343683/article/details/125240847 \n\n

**qq头像接口:**\n
https://q1.qlogo.cn/g?b=qq&nk=(qq号)&s=640

\n

**q群头像接口:**\n
https://p.qlogo.cn/gh/(qq群号)/(qq群号)/640/
`;

export function apply(ctx: Context, config: Config) {

  ctx.command('获取群头像', "获取群头像")
    .alias('aga')
    .option("opt_url_flag", '-u, --url')
    .action(async ({session, options}) => {

      if( config.verboseSessionOutput ) 
        await ctx.logger.info(`[debug]session.platform: ${session.platform}, session.channelId: ${session.channelId}`);

      if ( !(session.channelId && session.platform === 'onebot') ) {
        await session.send( '[error]请在onebot-qq群聊中使用此命令。' );
        return;
      }

      const gid = session.guildId;
      const guildAvatarUrl = `https://p.qlogo.cn/gh/${gid}/${gid}/640`;

      try{

        let msg = [];
        if ( options.opt_url_flag ){
          if ( config.verboseSessionOutput )
            msg.push(`[debug]options里面有url的flag，所以这次发送的是url\n`);
          msg.push(h.text(`\t↓ 群头像链接 ↓\n\t${guildAvatarUrl}\n`));
        } else {
          if ( config.verboseSessionOutput )
            msg.push(`[debug]options里面没加url的flag，所以这次发送的是图片\n`);
          msg.push(h.text('\t↓ 群头像 ↓\n'));
          if ( config.verboseSessionOutput )
            msg.push(h.text(`\n[debug]头像Url: ${guildAvatarUrl}\n`));
          msg.push(h.image(guildAvatarUrl));
        }
        await session.send(msg);
        
      } catch (err) {

        let errMsg = `[error]获取群头像失败: ${err}`;
        await session.send(errMsg);
        await ctx.logger.error(errMsg);

      }

    });


    ctx.command(
      '获取头像 [arg0_qquid]',
      '优先级: at的用户 > 传入的qqid > 指令使用者自身'
    )
    .option("opt_url_flag", '-u, --url')
    .alias('get_qq_avatar')
    .action(async ({session, options}, arg0_qquid) => {
      if( config.verboseSessionOutput ) 
        await ctx.logger.info(`[debug]session.platform: ${session.platform}, session.channelId: ${session.channelId}`);

      let qquid;
      let QUID_SOURCE;

      let at_user = null;
      for ( const e of session.event.message.elements ){
        if ( e.type === "at" ){
          at_user = e; break;
        }
      }

      if ( at_user !== null ){
        QUID_SOURCE = "AT";
        qquid = at_user.attrs.id;
      } else if ( arg0_qquid !== undefined ) {
        QUID_SOURCE = "PARAM";
        qquid = arg0_qquid;
      } else {
        QUID_SOURCE = "SELF";
        qquid = session.userId;
      }

      let quidMsg = ``;
      quidMsg += `[debug]获取QQ头像的QUID来源: ${QUID_SOURCE}\n`;
      quidMsg += `[debug]获取QQ头像的QUID: ${qquid}\n`;

      if ( config.verboseSessionOutput )
        await session.send(quidMsg);
      await ctx.logger.info(quidMsg);


      const qqAvatarUrl = `https://q1.qlogo.cn/g?b=qq&nk=${qquid}&s=640`;

      try{

        let msg = [];
        if ( options.opt_url_flag ){
          if ( config.verboseSessionOutput )
            msg.push(`[debug]options里面有url的flag，所以这次发送的是url\n`)
          msg.push(h.text(`\t↓ QQ头像链接↓ \n\t${qqAvatarUrl}\n`));
        } else {
          if ( config.verboseSessionOutput )
            msg.push(`[debug]options里面没加url的flag，所以这次发送的是图片\n`);
          msg.push(h.text('\t↓ QQ头像 ↓\n'));
          if ( config.verboseSessionOutput )
            msg.push(h.text(`\n[debug]头像Url: ${qqAvatarUrl}\n`));
          msg.push(h.image(qqAvatarUrl));
        }
        await session.send(msg);

      } catch (err) {

        let errMsg = `[error]获取QQ头像失败: ${err}`;
        await session.send(errMsg);
        await ctx.logger.error(errMsg);

      }

    });

}
